/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.support.scripting;

import cn.easyplatform.lang.Lang;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.vos.fx.PriceVo;
import cn.easyplatform.spi.service.AddonService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.service.ServiceLocator;
import cn.easyplatform.web.task.EventSupport;
import cn.easyplatform.web.task.zkex.ListSupport;
import cn.easyplatform.web.task.MainTaskSupport;
import cn.easyplatform.web.task.zkex.list.PanelSupport;
import cn.easyplatform.web.utils.PageUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.zkoss.zk.ui.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class FxUtils {

    private EventSupport handler;

    public FxUtils(EventSupport handler) {
        this.handler = handler;
    }

    /**
     * 把当前页绑定的栏位打包
     *
     * @return
     */
    public final String pack() {
        MainTaskSupport support = null;
        if (handler instanceof MainTaskSupport)
            support = (MainTaskSupport) handler;
        else if (handler instanceof ListSupport
                || handler instanceof PanelSupport) {
            if (handler instanceof ListSupport) {
                support = (MainTaskSupport) ((ListSupport) handler).getMainHandler();
            } else
                support = (MainTaskSupport) ((PanelSupport) handler).getList().getMainHandler();
        }
        Map<String, Object> data = new HashMap<String, Object>();
        for (Component comp : support.getManagedInputComponents())
            data.put(comp.getId().toUpperCase(), PageUtils.getValue(comp, false));
        try {
            return new ObjectMapper().writeValueAsString(data);
        } catch (JsonProcessingException e) {
            throw Lang.wrapThrow(e);
        }
    }

    /**
     * 把打包好的数据解包到页面
     *
     * @param json
     */
    public final void unpack(String json) {
        try {
            Map<String, Object> data = new ObjectMapper().readValue(json, Map.class);
            MainTaskSupport support = null;
            if (handler instanceof MainTaskSupport)
                support = (MainTaskSupport) handler;
            else if (handler instanceof ListSupport
                    || handler instanceof PanelSupport) {
                if (handler instanceof ListSupport) {
                    support = (MainTaskSupport) ((ListSupport) handler).getMainHandler();
                } else
                    support = (MainTaskSupport) ((PanelSupport) handler).getList().getMainHandler();
            }
            Iterator<Map.Entry<String, Object>> itr = data.entrySet().iterator();
            while (itr.hasNext()) {
                Map.Entry<String, Object> entry = itr.next();
                for (Component comp : support.getManagedInputComponents()) {
                    if (comp.getId().equalsIgnoreCase(entry.getKey())) {
                        PageUtils.setValue(comp, entry.getValue());
                        itr.remove();
                        break;
                    }
                }
            }
        } catch (IOException e) {
            throw Lang.wrapThrow(e);
        }
    }

    /**
     * 获取即期价格
     *
     * @param base
     * @param terms
     * @param market
     * @return
     */
    public double[] getSpot(String base, String terms, String market) {
        AddonService as = ServiceLocator.lookup(AddonService.class);
        IResponseMessage resp = as.getSpot(new SimpleRequestMessage(new PriceVo(base, terms, market)));
        if (resp.isSuccess())
            return (double[]) resp.getBody();
        return new double[]{0, 0};
    }

    /**
     * 获取远期价格
     *
     * @param base
     * @param terms
     * @param tenor
     * @param market
     * @return
     */
    public double[] getForward(String base, String terms, String tenor, String market) {
        AddonService as = ServiceLocator.lookup(AddonService.class);
        IResponseMessage resp = as.getForward(new SimpleRequestMessage(new PriceVo(base, terms, tenor, market)));
        if (resp.isSuccess())
            return (double[]) resp.getBody();
        return new double[]{0, 0};
    }
}
